package com.jia.interviewPro;

import java.util.Stack;

/**
 * 面试题 03.04. 化栈为队
 */
public class Pro0304 {
    Stack<Integer> s1 = new Stack<>();
    Stack<Integer> s2 = new Stack<>();
    /** Initialize your data structure here. */
    public Pro0304() {

    }

    /** Push element x to the back of queue. */
    public void push(int x) {
        if(!s2.isEmpty()) {
            Stack<Integer> tmp = s1;
            s1 = s2;
            s2 = tmp;
        }
        s1.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(empty()) { throw new RuntimeException("empty."); }
        if(!s2.isEmpty()) {
            Stack<Integer> tmp = s1;
            s1 = s2;
            s2 = tmp;
        }
        while(!s1.isEmpty()) {
            s2.push(s1.pop());
        }
        int ret = s2.pop();
        while(!s2.isEmpty()) {
            s1.push(s2.pop());
        }
        return ret;
    }

    /** Get the front element. */
    public int peek() {
        if(empty()) { throw new RuntimeException("empty."); }
        if(!s2.isEmpty()) {
            Stack<Integer> tmp = s1;
            s1 = s2;
            s2 = tmp;
        }
        while(!s1.isEmpty()) {
            s2.push(s1.pop());
        }
        int ret = s2.peek();
        while(!s2.isEmpty()) {
            s1.push(s2.pop());
        }
        return ret;
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return s1.isEmpty() && s2.isEmpty();
    }
}
